#include "searchinblobs.h"
#include "constants.h"
#include "delegate.h"
#include "tools.h"
#include "result.h"

#include <QDebug>
#include <QSqlQuery>
#include <QSqlError>
#include <QTextCodec>
#include <QFile>
#include <QTextStream>
#include <QDate>
#include <QMessageBox>
#include <QPrintDialog>
#include <QPrinter>

using namespace Constants;
using namespace ToolsSpace;



Searchinblobs::Searchinblobs(QObject * parent)
{
    Q_UNUSED(parent);
    setupUi(this);
    setAttribute(Qt::WA_DeleteOnClose);
    Tools tool;
    m_pathToPersoDatas = tool.pathToPersonalDatas();
    connect(quitButton,SIGNAL(pressed()),this,SLOT(close()));
    connect(searchButton,SIGNAL(pressed()),this,SLOT(parse()));
    connect(addButton,SIGNAL(pressed()),this,SLOT(addarequest()));
    connect(deleteButton,SIGNAL(pressed()),this,SLOT(deleterequest()));
    connect(printButton,SIGNAL(pressed()),this,SLOT(print()));
    
}

Searchinblobs::~Searchinblobs()
{
    qWarning() << __FILE__ << QString::number(__LINE__) << "destructeur Searchinblobs" ;
}

void Searchinblobs::setMedintuxUser(QString medintuxuser)
{
    m_medintuxuser = medintuxuser;
}

void Searchinblobs::initialise()
{
    m_db = QSqlDatabase::database("DrTuxTest");
    //USERS
    QSqlQuery qUsers(m_db);
    QString reqUsers = QString("select %1 from %2").arg("Login","Personnes");
    if (!qUsers.exec(reqUsers))
    {
          qWarning() << __FILE__ << QString::number(__LINE__) << "unable to get users : " << qUsers.lastError().text() ;
        }
    QStringList listofusers;
    listofusers << m_medintuxuser;
    while (qUsers.next())
    {
        QString login = qUsers.value(0).toString();
        if (!login.isEmpty())
        {
              listofusers << login;
            }
        }
    listofusers.removeDuplicates();
    loginBox->addItems(listofusers);
    //choix de documents
    QStringList listOfDocumentsHeads;
    listOfDocumentsHeads << "Tous";
    QSqlQuery qyDocuments(m_db); 
    QString reqDocuments = QString("select %1 from %2 where %3 = '%4'").arg("RbDate_NomDate","RubriquesHead","RbDate_TypeRub","20080000");
    if (!qyDocuments.exec(reqDocuments))
    {
          qWarning() << __FILE__ << QString::number(__LINE__) << qyDocuments.lastError().text() ;
        }
    while (qyDocuments.next())
    {
        listOfDocumentsHeads << qyDocuments.value(0).toString();
        }        
    listOfDocumentsHeads.removeDuplicates();
    listOfDocumentsHeads.sort();
    documentsComboBox->addItems(listOfDocumentsHeads);
    Tools t(this);
    m_hashConditions = t.hashOfConditionDelegateCombo();
    m_analyseModel = new QStandardItemModel(1,ModelResearchFieldsMaxParam,this);
    m_analyseModel->setHeaderData(CONJONCTION,Qt::Horizontal,trUtf8("Conjonction"));
    m_analyseModel->setHeaderData(VARIABLE,Qt::Horizontal,trUtf8("Variable"));
    m_analyseModel->setHeaderData(CONDITIONOFRESEARCH,Qt::Horizontal,trUtf8("Condition"));
    m_analyseModel->setHeaderData(COMPAREVARIABLE,Qt::Horizontal,trUtf8("Autre variable"));
    m_analyseModel->setHeaderData(DATEBEGIN,Qt::Horizontal,trUtf8("Date de début"));
    m_analyseModel->setHeaderData(DATEEND,Qt::Horizontal,trUtf8("Date de fin"));
    m_analyseModel->setHeaderData(TYPEOFDOC,Qt::Horizontal,trUtf8("Dans type"));
    m_analyseModel->setHeaderData(INDEXOFVALUE,Qt::Horizontal,trUtf8("Index de la valeur"));
    m_analyseModel->setHeaderData(TOKENEDIT,Qt::Horizontal,trUtf8("Etiquette dans le terrain"));
    m_analyseModel->setData(m_analyseModel->index(0,VARIABLE),trUtf8("Patient"),Qt::EditRole);
    tableView->setModel(m_analyseModel); 
    tableView->setItemDelegateForColumn(CONJONCTION,new ComboDelegate(this));
    tableView->setItemDelegateForColumn(CONDITIONOFRESEARCH,new ComboDelegate(this));
    tableView->setItemDelegateForColumn(DATEBEGIN,new DateDelegate(this));
    tableView->setItemDelegateForColumn(DATEEND,new DateDelegate(this));
    tableView->setItemDelegateForColumn(TYPEOFDOC,new ComboDelegate(this));
    tableView->setItemDelegateForColumn(TOKENEDIT,new TokenTerrainDelegate(this)); 
    tableView->setItemDelegateForColumn(INDEXOFVALUE,new IndexOfValueInLineDelegate(this));
    
    m_resultsModel = new QStandardItemModel;//0,FieldsModelResults_MaxParam,this);
}

void Searchinblobs::parse()
{
    
    QStringList listofIdReturned;
    for (int row = 0; row < m_analyseModel->rowCount(); ++row)
    {
        textEdit->setHtml("");
        Result rt(this);
        Tools t(this);
        QString choiceOfCondition = m_analyseModel->data(m_analyseModel->index(row,CONDITIONOFRESEARCH),Qt::DisplayRole).toString();
        int condition = m_hashConditions.key(choiceOfCondition);
        QString variable = m_analyseModel->data(m_analyseModel->index(row,VARIABLE),Qt::DisplayRole).toString();
        QString comparevariable = m_analyseModel->data(m_analyseModel->index(row,COMPAREVARIABLE),Qt::DisplayRole).toString();
        QString conjunction = m_analyseModel->data(m_analyseModel->index(row,CONJONCTION),Qt::DisplayRole).toString();
        int rowOfConjunction = t.hashOfConjonctions().key(conjunction);
        QString tableblobs = "RubriquesBlobs";
        QString idprimkey = "RbDate_PrimKey";
        QString blob = "RbDate_DataRub";
        QString refDos = "RbDate_IDDos";
        if (!m_db.tables().contains(tableblobs))
        {
              tableblobs = "rubriquesblobs";
            }
        QStringList resultsList;
        switch(condition){
            case CONTAINS :
                resultsList = allIdWitchContainsVariable(comparevariable,row);
                break;
            case INF :
                resultsList = allIdWhoseVariableIsInfOrSupTo(variable,comparevariable,row,INF);
                break;
            case SUP :
                resultsList = allIdWhoseVariableIsInfOrSupTo(variable,comparevariable,row,SUP);
                break;
            default :
                break;
            }
            rt.setResults(setHashIdAndNamesOfResults(resultsList));
            if (rt.exec() == QDialog::Accepted)
            {
                 switch(rowOfConjunction){
                     case AND :
                         m_listOfReturnedIdWithConjunction = rt.getListOfId();
                         break;
                     case OR :
                         m_listOfReturnedIdWithConjunction << rt.getListOfId();
                         m_listOfReturnedIdWithConjunction.removeDuplicates();
                         break;
                     default :
                         m_listOfReturnedIdWithConjunction = rt.getListOfId();
                         break;
                     }
                }
        }//for        
}

QStringList Searchinblobs::allIdWitchContainsVariable(QString comparevariable,int row)
{
    enum reqBlob
    {
        BLOB=0,
        REFDOS
        };
    Tools t;
    QDate beginDate = m_analyseModel->data(m_analyseModel->index(row,DATEBEGIN),Qt::DisplayRole).toDate();
    QDate endDate = m_analyseModel->data(m_analyseModel->index(row,DATEEND),Qt::DisplayRole).toDate();
    QString begin = beginDate.toString("yyyy-MM-dd");
    QString end = endDate.toString("yyyy-MM-dd");
    QString typeblob = m_analyseModel->data(m_analyseModel-> index(row,TYPEOFDOC),Qt::DisplayRole).toString();
    QString numbertype = t.hashOfTypesOfHeads().key(typeblob);
    QStringList list;
    QStringList listOfConcernedBlobs;
    QString tablehead = "RubriquesHead";
    if (!m_db.tables().contains(tablehead))
        {
              tablehead = "rubriqueshead";
            }
    QString tableblobs = "RubriquesBlobs";
    QString idprimkeyblob = "RbDate_PrimKey";
    QString blob = "RbDate_DataRub";
    QString refDos = "RbDate_IDDos";
    if (!m_db.tables().contains(tableblobs))
    {
        tableblobs = "rubriquesblobs";
            }
    QStringList listOfStudiedIds = m_listOfReturnedIdWithConjunction;
    if(listOfStudiedIds.size()<1)
    {
    qDebug() << __FILE__ << "repere : " << QString::number(__LINE__) << "listofidstudied < 1 ";
    QSqlQuery qHead(m_db);
    QString reqHead = QString("select %1 from %2")
                             .arg("RbDate_RefBlobs_Primkey",tablehead);

    reqHead += QString(" where %1 = '%2' ").arg("RbDate_TypeRub",numbertype);
    reqHead += QString(" and %1 between '%2' and '%3'").arg("RbDate_Date",begin,end);
    reqHead += QString(" and %1 = '%2'").arg("RbDate_CreateUser",loginBox->currentText());
    if (!qHead.exec(reqHead))
    {
          qWarning() << __FILE__ << QString::number(__LINE__) << qHead.lastError().text() ;
          }
    while (qHead.next())
    {
        listOfConcernedBlobs << qHead.value(0).toString();
        }
    foreach(QString idblob,listOfConcernedBlobs){
        QSqlQuery qy(m_db);
        QString reqBlob = QString("select %1,%2 from %3 where %4 = '%5'").arg(blob,refDos,tableblobs,idprimkeyblob,idblob);
        //qDebug() << __FILE__ << "repere : " << QString::number(__LINE__) << reqBlob;
        //reqBlob += " and RbDate_IDDos='1121'";
        if (!qy.exec(reqBlob))
        {
              qWarning() << __FILE__ << QString::number(__LINE__) << qy.lastError().text() ;
              return QStringList();
            }
        while (qy.next())
        {
            QVariant blob = qy.value(BLOB);
            QString refdos = qy.value(REFDOS).toString();
            QTextCodec* codec = QTextCodec::codecForName("utf-8");
            QString blobstring = codec->toUnicode(blob.toByteArray ()) ;
            if (blobstring.contains(comparevariable))
            {
                list << refdos;
                }
            }
        }//foreach
    } //if
    else{
    QSqlQuery qHead(m_db);
    QString reqHead = QString("select %1 from %2")
                             .arg("RbDate_RefBlobs_Primkey",tablehead);

    reqHead += QString(" where %1 = '%2' ").arg("RbDate_TypeRub",numbertype);
    reqHead += QString(" and %1 between '%2' and '%3'").arg("RbDate_Date",begin,end);
    reqHead += QString(" and %1 = '%2'").arg("RbDate_CreateUser",loginBox->currentText());
    if (!qHead.exec(reqHead))
    {
          qWarning() << __FILE__ << QString::number(__LINE__) << qHead.lastError().text() ;
          }
    while (qHead.next())
    {
        listOfConcernedBlobs << qHead.value(0).toString();
        }
    foreach(QString idblob,listOfConcernedBlobs){
        QSqlQuery qy(m_db);
        QString reqBlob = QString("select %1,%2 from %3 where %4 = '%5'").arg(blob,refDos,tableblobs,idprimkeyblob,idblob);
        //reqBlob += " and RbDate_IDDos='1121'";
        if (!qy.exec(reqBlob))
        {
              qWarning() << __FILE__ << QString::number(__LINE__) << qy.lastError().text() ;
              return QStringList();
            }
        while (qy.next())
        {
            QVariant blob = qy.value(BLOB);
            QString refdos = qy.value(REFDOS).toString();
            QTextCodec* codec = QTextCodec::codecForName("utf-8");
            QString blobstring = codec->toUnicode(blob.toByteArray ()) ;
            if (blobstring.contains(comparevariable))
            {
                if (listOfStudiedIds.contains(refdos))
                {
                    list << refdos;
                    }
                
                }
            }
        }//foreach
        }//else
    qDebug() << __FILE__ << "repere : " << QString::number(__LINE__)<< "list = " << QString::number(list.size());
    return list;
}



QStringList Searchinblobs::allIdWhoseVariableIsInfOrSupTo(QString variable,QString comparevariable,int row, int compare)
{
    qDebug() << __FILE__ << QString::number(__LINE__) << " in allIdWhoseVariableIsInfOrSupTo " ;
    qDebug() << __FILE__ << QString::number(__LINE__) << "QString variable,QString comparevariable,int row  =" << variable
                                                                                                                << comparevariable
                                                                                                                << QString::number(row) ;
    QApplication::setOverrideCursor(Qt::WaitCursor);
    enum reqBlob
    {
        BLOB=0,
        REFDOS
        };
    Tools t(this);
    QString conjunction = m_analyseModel->data(m_analyseModel->index(row,CONJONCTION),Qt::DisplayRole).toString();
    int rowOfConjunction = t.hashOfConjonctions().key(conjunction);
    QDate beginDate = m_analyseModel->data(m_analyseModel->index(row,DATEBEGIN),Qt::DisplayRole).toDate();
    QDate endDate = m_analyseModel->data(m_analyseModel->index(row,DATEEND),Qt::DisplayRole).toDate();
    QString typeblob = m_analyseModel->data(m_analyseModel-> index(row,TYPEOFDOC),Qt::DisplayRole).toString();
    QString stringOfIndexOfNumberToCompare = m_analyseModel->data(m_analyseModel-> index(row,INDEXOFVALUE),Qt::DisplayRole).toString();
    int indexOfNumberToCompare = 0;
    if (!stringOfIndexOfNumberToCompare.contains("auto"))
    {
          indexOfNumberToCompare = stringOfIndexOfNumberToCompare.toInt();
        }
    QString numbertype = t.hashOfTypesOfHeads().key(typeblob);
    int type = t.hashIntAndTypeStringsOfHeads().key(typeblob);
    QString begin = beginDate.toString("yyyy-MM-dd");
    QString end = endDate.toString("yyyy-MM-dd");
    QStringList listOfStudiedIds;
    switch(rowOfConjunction){
        case AND :
            qDebug() << __FILE__ << QString::number(__LINE__) << " in AND ";
            listOfStudiedIds = m_listOfReturnedIdWithConjunction;
            qDebug() << __FILE__ << QString::number(__LINE__) << " listOfStudiedIds =" << QString::number(listOfStudiedIds.size()) ;
            break;
        case OR :
            qDebug() << __FILE__ << QString::number(__LINE__) << " in OR ";
            listOfStudiedIds = m_listOfReturnedIdWithConjunction;
            break;
        default :
            qDebug() << __FILE__ << QString::number(__LINE__) << " in default ";
            listOfStudiedIds = m_listOfReturnedIdWithConjunction;
            break;    
        }
    QFile fileForTest(qApp->applicationDirPath()+"/lines.txt");
    if (!fileForTest.open(QIODevice::WriteOnly))
    {
        qWarning() << __FILE__ << QString::number(__LINE__) << "unable to write on lines.txt" ;
        }
    QTextStream streamForTest(&fileForTest);
    QFile fileNumbers(qApp->applicationDirPath()+"/numbers.txt");
    if (!fileNumbers.open(QIODevice::WriteOnly))
    {
          qWarning() << __FILE__ << QString::number(__LINE__) << "unable to write on numbers.txt" ;
        }
    QTextStream streamNumbers(&fileNumbers);

    QString tableblobs = "RubriquesBlobs";
    QString idprimkeyblob = "RbDate_PrimKey";
    QString blob = "RbDate_DataRub";
    QString refDos = "RbDate_IDDos";
    if (!m_db.tables().contains(tableblobs))
    {
        tableblobs = "rubriquesblobs";
            }
    QStringList listOfId;
    QString tablehead = "RubriquesHead";
    if (!m_db.tables().contains(tablehead))
    {
        tablehead = "rubriqueshead";
        }
    QStringList listOfConcernedBlobs;
    QSqlQuery qHeads(m_db);

    if (listOfStudiedIds.size()<1)
    {
        QString requeteHead = QString("select %1 from %2 where %3 = '%4'")
                             .arg("RbDate_RefBlobs_Primkey",tablehead,"RbDate_TypeRub",numbertype);                             
                             
              if (type!=TERRAIN){
                     requeteHead += QString(" and %1 between '%2' and '%3'").arg("RbDate_Date",begin,end);
                                 }
              if (type == DOCUMENTS && !documentsComboBox->currentText().contains("Tous"))
              {
                    requeteHead += QString(" and %1 = '%2'").arg("RbDate_NomDate",documentsComboBox->currentText());
                  }
                             qDebug() << __FILE__ << QString::number(__LINE__) << " requete =" << requeteHead ;
        if (!qHeads.exec(requeteHead))
        {
            qWarning() << __FILE__ << QString::number(__LINE__) << qHeads.lastError().text() ;
            }
        while (qHeads.next())
        {
            QString idBlog = qHeads.value(0).toString();
            listOfConcernedBlobs << idBlog;
            }qDebug() << __FILE__ << QString::number(__LINE__) << " listOfConcernedBlobs =" << QString::number(listOfConcernedBlobs.size()) ;
        }
    else
    {
        qDebug() << __FILE__ << QString::number(__LINE__) << "listOfStudiedIds.size()  =" << QString::number(listOfStudiedIds.size()) ;
        for (int i = 0; i < listOfStudiedIds.size(); ++i)
        {
              QString requeteHead = QString("select %1 from %2 where %3 = '%4'")
                             .arg("RbDate_RefBlobs_Primkey",tablehead,"RbDate_TypeRub",numbertype);
                             //qDebug() << __FILE__ << QString::number(__LINE__) << " requete =" << requeteHead ;
            
              if (type!=TERRAIN)
                {
                    requeteHead += QString(" and %1 between '%2' and '%3'").arg("RbDate_Date",begin,end);//dans terrain les dates sont différentes des dates de création (terrain créé une seule fois)
                    }
              if (type == DOCUMENTS && !documentsComboBox->currentText().contains("Tous"))
              {
                    requeteHead += QString(" and %1 = '%2'").arg("RbDate_NomDate",documentsComboBox->currentText());
                  }
              QString guid = listOfStudiedIds[i];
              requeteHead += QString(" and %1 = '%2'").arg("RbDate_IDDos",guid);
              //qDebug() << __FILE__ << QString::number(__LINE__) << " requeteHead =" << requeteHead ;
              if (!qHeads.exec(requeteHead))
              {
                  qWarning() << __FILE__ << QString::number(__LINE__) << qHeads.lastError().text() ;
                  }
              while (qHeads.next())
              {
                  QString idBlog = qHeads.value(0).toString();
                  listOfConcernedBlobs << idBlog;
                  }
            }//for
            qDebug() << __FILE__ << QString::number(__LINE__) << " listOfConcernedBlobs =" << QString::number(listOfConcernedBlobs.size()) ;
       
        }

    switch(type){
        case DOCUMENTS :
            foreach(QString idblob,listOfConcernedBlobs){
                    listOfId << searchInfInDocuments(blob,refDos,tableblobs,idprimkeyblob,idblob,variable,
                                                     comparevariable,indexOfNumberToCompare,compare);
                    }
            break;
        case TERRAIN :
            foreach(QString idblob,listOfConcernedBlobs){qDebug() << __FILE__ << QString::number(__LINE__) << " lis =" << QString::number(listOfConcernedBlobs.size()) ;
                listOfId << searchInTerrain(blob,refDos,tableblobs,idprimkeyblob,idblob,variable,comparevariable,row,begin,end,compare);
                }
            break;
        case OBSERVATION :
            foreach(QString idblob,listOfConcernedBlobs){
                listOfId << searchInObservation(blob,refDos,tableblobs,idprimkeyblob,idblob,variable,comparevariable,row);
                }
            break;
        default :
            break;    
        }
    QApplication::restoreOverrideCursor();
    return listOfId;
}

QHash<QString,QString> Searchinblobs::setHashIdAndNamesOfResults(QStringList resultsList)
{
    QHash<QString,QString> hash;
    QString nomDoss = "FchGnrl_NomDos";
    QString prenomDoss = "FchGnrl_Prenom";
    QString idDoss = "FchGnrl_IDDos";
    QString table = "IndexNomPrenom";
    if (!m_db.tables().contains(table))
        {
              table = "indexnomprenom";
            }
    foreach(QString idstring,resultsList){
        QSqlQuery query(m_db);
        QString requete = QString("select %1 , %2 from %3 where %4 = '%5'").arg(nomDoss,prenomDoss,table,idDoss,idstring);
        //qDebug() << __FILE__ << QString::number(__LINE__) << " requete =" << requete ;
        if (!query.exec(requete))
        {
              qWarning() << __FILE__ << QString::number(__LINE__) << query.lastError().text() ;
              return QHash<QString,QString>();
            }
        while (query.next())
        {
            QString name = query.value(NAME).toString();
            QString surname = query.value(SURNAME).toString();
            hash.insert(idstring,name+";"+surname);
            }
        }
    return hash;
}

QStringList Searchinblobs::searchInObservation(QString blob,QString refDos,QString tableblobs,QString idprimkeyblob,QString idblob,QString variable,QString comparevariable,int row)
{
    enum reqBlob
    {
        BLOB=0,
        REFDOS
        };
    enum inLine
    {
        TEXT_INLINE=0,
        RESULT_INLINE
        };
    enum TypeOfValueToCompare
    {
        SIMPLEVALUE=0,
        VALUESEPARATEDBYSLASH
        };
        int typeofvaluetocompare = 0;
        if (comparevariable.contains(QRegExp("[0-9]/[0-9]")))
        {
              typeofvaluetocompare = int(VALUESEPARATEDBYSLASH);
            }
        //int a = indexOfNumberToCompare;
        QRegExp span = QRegExp("</span>");
        QRegExp spanstylebefore = QRegExp("<span style=\"font-family:Arial;font-size:.*pt;font-weight:600;color:#0000ff\">");
        QRegExp spanstyleafter = QRegExp("<span style=\"font-family:Arial;font-size:.*pt\">");
        QString result;
        QSqlQuery qy(m_db);
        QStringList listOfId;
        QString reqBlob = QString("select %1,%2 from %3 where %4 = '%5'").arg(blob,refDos,tableblobs,idprimkeyblob,idblob);
        //reqBlob += " and RbDate_IDDos='1121'";
        if (!qy.exec(reqBlob))
        {
              qWarning() << __FILE__ << QString::number(__LINE__) << qy.lastError().text() ;
              return QStringList();
            }
        while (qy.next())
        {
            QString blob = qy.value(BLOB).toString();
            QString refdos = qy.value(REFDOS).toString();
            QStringList bloblist;
            if (blob.contains("<br />"))
            {
                  bloblist = blob.split("<br />");
                  }
            else if (blob.contains("<br/>"))
            {
                  bloblist = blob.split("<br/>");
                }
            else if (blob.contains("</p>"))
            {
                  bloblist = blob.split("</p>");
                }
            
            else
            {
                qWarning() << __FILE__ << QString::number(__LINE__) << "pas de separateur retrouve" ;
                return QStringList();
                }
            qDebug() << __FILE__ << QString::number(__LINE__) << "variable = " << variable ;
            foreach(QString line,bloblist){
                if (line.contains(variable))
                {
                      line.remove(span);
                      line.remove(spanstylebefore);
                      line.remove(spanstyleafter);
                      qDebug() << __FILE__ << QString::number(__LINE__) << " line  =" << line ;
                      if (line.contains(":"))
                      {
                            QStringList listinline;
                            listinline = line.split(":");
                            if (listinline.size()>1)
                            {
                                  result = listinline[RESULT_INLINE];
                                }
                          }
                    }
                }
            
            
            if (result.contains(QRegExp("[a-z]",Qt::CaseInsensitive)))
            {
                  QStringList list;
                  list = result.split(" ",QString::SkipEmptyParts);
                  foreach(QString item,list){
                      if (item.contains(QRegExp("[0-9]/[0-9]"))&& typeofvaluetocompare == VALUESEPARATEDBYSLASH)
                      {
                            QStringList l;
                            l = item.split("/");
                            result = l.join("+");
                            QStringList ltocompare;
                            ltocompare = comparevariable.split("/");
                            if (l[0].toInt() <= ltocompare[0].toInt() && l[1].toInt() <= ltocompare[1].toInt())
                            {
                                  listOfId << refdos;
                                }
                            else // pour ne garder que la derniere valeur de TA
                            {
                                if (listOfId.contains(refdos))
                                {
                                      listOfId.removeAll(refdos);
                                    }
                                }
                          }
                      else if (item.contains(QRegExp("[0-9]"))&& typeofvaluetocompare == SIMPLEVALUE)
                      {
                            result = item;
                            if (result.toInt() < comparevariable.toInt())
                            {
                                  listOfId << refdos;
                                }
                          }
                      else
                      {
                          qWarning() << __FILE__ << QString::number(__LINE__) << "no numbers found , result = " << result;
                          }
                }
            }
            else
            {
                if (result.contains(QRegExp("[0-9]/[0-9]"))&& typeofvaluetocompare == VALUESEPARATEDBYSLASH)
                {
                            QStringList l;
                            l = result.split("/");
                            result = l.join("+");
                            QStringList ltocompare;
                            ltocompare = comparevariable.split("/");
                            if (l[0].toInt() <= ltocompare[0].toInt() && l[1].toInt() <= ltocompare[1].toInt())
                            {
                                  listOfId << refdos;
                                  QString exline = textEdit->toHtml();
                                  exline += result+":"+refdos+"<br/>";
                                  textEdit->setHtml(exline);
                                }
                          }
                else if (result.contains(QRegExp("[0-9]"))&& typeofvaluetocompare == SIMPLEVALUE)
                {
                      if (result.toInt() < comparevariable.toInt())
                      {
                            listOfId << refdos;
                          }
                    }
                else
                {
                    qWarning() << __FILE__ << QString::number(__LINE__) << "no numbers found , result = " << result;
                    }
                }
                }//while q.next()
    return listOfId;
}

QStringList Searchinblobs::searchInfInDocuments(QString blob,QString refDos,QString tableblobs,QString idprimkeyblob,QString idblob,QString variable,
                                                QString comparevariable, int indexOfNumberToCompare, int compare)
{
    enum reqBlob
    {
        BLOB=0,
        REFDOS
        };
        int indexofvalue = indexOfNumberToCompare;
        QSqlQuery qy(m_db);
        QStringList listOfId;
        QString reqBlob = QString("select %1,%2 from %3 where %4 = '%5'").arg(blob,refDos,tableblobs,idprimkeyblob,idblob);
        //reqBlob += " and RbDate_IDDos='1121'";
        if (!qy.exec(reqBlob))
        {
              qWarning() << __FILE__ << QString::number(__LINE__) << qy.lastError().text() ;
              return QStringList();
            }
        while (qy.next())
        {
            QString blob = qy.value(BLOB).toString();
            QString refdos = qy.value(REFDOS).toString();
            QStringList bloblist;
            //qDebug() << __FILE__ << QString::number(__LINE__) << " blob =" << blob ;
            if (blob.contains("<br />"))
            {
                  bloblist = blob.split("<br />");
                  }
            else if (blob.contains("<br/>"))
            {
                  bloblist = blob.split("<br/>");
                }
            else if (blob.contains("</p>"))
            {
                  bloblist = blob.split("</p>");
                }
            
            else
            {
                //QMessageBox::warning(0,trUtf8("Warning"),trUtf8("blob ne contient pas de séparateur connu"),QMessageBox::Ok);
                qWarning() << __FILE__ << QString::number(__LINE__) << trUtf8("blob ne contient pas de séparateur connu") ;
                return QStringList();
                }
                
            //qDebug() << __FILE__ << QString::number(__LINE__) << " variable =" << variable ;
            if (blob.contains(variable,Qt::CaseInsensitive))
            {
                  foreach(QString line,bloblist){
                      if (line.contains(variable,Qt::CaseInsensitive)&& !line.contains("TEX") && !line.contains("RES"))
                      {
                            QStringList listInLine;
                            line.simplified();
                            listInLine = line.split(" ",QString::SkipEmptyParts);
                            listInLine.removeAll(".");
                            qDebug() << __FILE__ << QString::number(__LINE__) << " listInLine =" << listInLine.join("_") ;
                            if (listInLine.size()< indexofvalue)
                            {
                                  qWarning() << __FILE__ << QString::number(__LINE__) << "index to far" ;
                                  return QStringList();
                                }
                            int incrementalindex = 0;
                            foreach(QString w,listInLine)
                            {
                                bool conditiontest = false;
                                switch(compare){
                                    case INF :
                                        conditiontest = w.toDouble() < comparevariable.toDouble();
                                        break;
                                    case SUP :
                                        conditiontest = w.toDouble() > comparevariable.toDouble();
                                        break;
                                    default :
                                        break;    
                                    }  
                                qDebug() << __FILE__ << QString::number(__LINE__) << "w before = " << w;
                                /*if (indexofvalue <1 )
                                {
                                      continue;
                                    }*/
                                if (indexofvalue > 0 && w.contains(QRegExp("[0-9]"))  && !w.contains(QRegExp("[a-z]",Qt::CaseInsensitive)) && w == listInLine[indexofvalue -1])
                                {
                                      if (w.contains(","))
                                      {
                                            w.replace(",",".");
                                          }
                                    if (conditiontest)
                                    {
                                          qDebug() << __FILE__ << QString::number(__LINE__) << "w = " << w;
                                          listOfId << refdos;
                                        }
                                    }//if
                                else //auto
                                {                                    
                                    if (!testofdoubleregexp(w) )
                                    {
                                        if (incrementalindex > 10)
                                        {
                                              break;
                                            }
                                        ++incrementalindex;
                                        continue;                                       
                                        }                                    
                                    qWarning() << __FILE__ << QString::number(__LINE__) << "incrementalindex = " 
                                                   << QString::number(incrementalindex) ;
                                    if (w.contains(","))
                                        {
                                            w.replace(",",".");
                                          }
                                    if (conditiontest)
                                       {
                                            qWarning() << __FILE__ << QString::number(__LINE__) << "word number founded = " << w;
                                            listOfId << refdos;
                                            }
                                    else
                                    {
                                        break;
                                        }
                                        
                                    }//else
                                    QString exline = textEdit->toHtml();
                                    exline += line+":"+refdos+":"+findNameFirstnameFromMedintuxGuid(refdos)+"<br/>";
                                    textEdit->setHtml(exline);
                                    break;
                                }//foreach
                              }//if (line.contains(variable,Qt::CaseInsensitive)&& !line.contains("TEX") && !line.contains("RES"))
                      }//if blob contains
                   }//foreach(QString line,bloblist)
                
            }//while q.next()
    return listOfId;
}

QStringList Searchinblobs::searchInTerrain(QString blob,QString refDos,QString tableblobs,QString idprimkeyblob,
                                           QString idblob,QString variable,QString comparevariable,int row,
                                           QString begin,QString end, int compare)
{
    enum reqBlob
    {
        BLOB=0,
        REFDOS
        };
    QString namefirstname;      
    QDateTime datemin = QDateTime::fromString(begin,"yyyy-MM-dd");
    QDateTime datemax = QDateTime::fromString(end,"yyyy-MM-dd");
    QStringList listOfId;
    QSqlQuery qy(m_db);
    QString reqBlob = QString("select %1,%2 from %3 where %4 = '%5'").arg(blob,refDos,tableblobs,idprimkeyblob,idblob);
    if (!qy.exec(reqBlob))
    {
              qWarning() << __FILE__ << QString::number(__LINE__) << qy.lastError().text() ;
              return QStringList();
        }
    while (qy.next())
    {
        QString blob = qy.value(BLOB).toString();
        QString refdos = qy.value(REFDOS).toString();
        QString numbervalue;
        QString datetime;
        QDateTime valuedatetime;
        double result = 0.00;
        QString token;
        token = m_analyseModel->data(m_analyseModel-> index(row,TOKENEDIT),Qt::DisplayRole).toString();
        if (blob.contains(token))
        {
              qWarning() << __FILE__ << QString::number(__LINE__) << " token =" << token ;
              QStringList partedBlob = blob.split(token);
              if (partedBlob.size()<2)
              {
                    qWarning() << __FILE__ << QString::number(__LINE__) << "unable to part blob" ;
                    return QStringList();
                  }
              QString secondpart = partedBlob[1];
              QStringList secondpartlist;
              secondpartlist = secondpart.split("\n");
              QString datetimebefore;
              foreach(QString line,secondpartlist){
                  if (line.contains("["))
                  {
                        break;
                      }
                  if (line.contains("=")&& !line.contains("Mod"))
                  {
                        QStringList l = line.split("=");
                        if (l.size()>1)
                        {
                              datetime = l[0];//2009-01-19T14:47:39
                              datetime.replace("T",""); 
                              datetime.replace(" ","");
                              datetime.replace("\t","");//qDebug() << __FILE__ << QString::number(__LINE__) << " datetime =" << datetime ;
                              /*QDateTime*/valuedatetime = QDateTime::fromString(datetime,"yyyy-MM-ddhh:mm:ss");                             
                              if (valuedatetime>datemax)
                              {
                                    //qDebug() << __FILE__ << QString::number(__LINE__) << " break =" << valuedatetime.toString("yyyy-MM-ddhh:mm:ss") ;
                                    datetime = datetimebefore;
                                    break;
                                    }
                              numbervalue = l[1];
                              if (valuedatetime< datemin)
                              {
                                  numbervalue = 0.00;
                                  //qDebug() << __FILE__ << QString::number(__LINE__) << " continue =" << valuedatetime.toString("yyyy-MM-ddhh:mm:ss") ;                                  
                                  continue;
                                  }
                                    
                              if (numbervalue.contains(","))
                              {
                                    numbervalue.replace(",",".");
                                  }                     
                            datetimebefore = datetime;
                            }
                      }
                  }//foreach
        result = numbervalue.toDouble(); //qDebug() << __FILE__ << QString::number(__LINE__) << " result =" << QString::number(result) ;
        namefirstname = findNameFirstnameFromMedintuxGuid(refdos);
        bool conditiontest = false;
        switch(compare){
            case INF :
                conditiontest = result < comparevariable.toDouble();
                break;
            case SUP :
                conditiontest = result > comparevariable.toDouble();
                break;
            default :
                break;    
            }             
        if (conditiontest && result !=0.00)
        {
            listOfId << refdos;
            QString exline = textEdit->toHtml();
            exline += numbervalue+":"+datetime+":"+refdos+":"+namefirstname+"<br/>";
            textEdit->setHtml(exline);
            }
        }//if (blob.contains(token))
        }//while
        qDebug() << __FILE__ << QString::number(__LINE__) << " listOfId =" << listOfId.join(";") ;
    if (listOfId.size()>1)
    {
        QMessageBox::warning(0,tr("warning"),tr("Error : deux dossiers ou plus trouvés sur le même blob"),QMessageBox::Ok);
        return listOfId;
        }
    return listOfId;
}

void Searchinblobs::addarequest()
{
    if (!m_analyseModel->insertRows(m_analyseModel->rowCount(),1,QModelIndex()))
    {
          qWarning() << __FILE__ << QString::number(__LINE__) << "unable to insert row";
        }
    m_analyseModel->submit();
}

void Searchinblobs::deleterequest()
{
    int row = tableView->currentIndex().row();
    
    if (!m_analyseModel->removeRows(row,1,QModelIndex()))
    {
          qWarning() << __FILE__ << QString::number(__LINE__) << "unable to remove row" ;
        }
    m_analyseModel->submit();
}

bool Searchinblobs::testofdoubleregexp(const QString & word)
{
    bool test = false;
    //w.contains(QRegExp("[0-9]"))  && !w.contains(QRegExp("[a-z]",Qt::CaseInsensitive)) 
    if (word.contains(QRegExp("[0-9]"))  && !word.contains(QRegExp("[a-z]",Qt::CaseInsensitive)) )
    {
          test = true;
        }
    return test;
}

QString Searchinblobs::findNameFirstnameFromMedintuxGuid(const QString & refdos)
{
    QString namefirstname;    
    QSqlQuery qname(m_db);
    QString reqname = QString("select %1,%2 from %3 where %4 = '%5'")
                      .arg("FchGnrl_NomDos","FchGnrl_Prenom","IndexNomPrenom","FchGnrl_IDDos",refdos);
    if (!qname.exec(reqname))
    {
            qWarning() << __FILE__ << QString::number(__LINE__) << qname.lastError().text() ;
           }
    while (qname.next())
    {
            namefirstname = qname.value(0).toString()+","+qname.value(1).toString();
            } 
    return namefirstname;
}

void Searchinblobs::print()
{
    QString textDocument = textEdit->toPlainText();
    QTextDocument *doc = new QTextDocument(this);
    doc->setPlainText(textDocument);
    QPrinter *printer = new QPrinter;
    QPrintDialog *printdialog = new QPrintDialog(printer,this);
    printdialog               ->setWindowTitle(tr("Imprimer"));
    printdialog               ->exec();
    doc->print(printer);
}

QStringList Searchinblobs::findIdOfPatientsWhoHaveConsulted(QStringList & listid)//TODO modifier liste id sur demande de l utilisateur
{
    QStringList idlist;
    QStringList listidreturned;    
    QDate beginDate = beginDateEdit->date();
    QString beginDateStr = beginDate.toString("yyyy-MM-dd");
    QDate endDate = endDateEdit->date();
    QString endDateStr = endDate.toString("yyyy-MM-dd");
    QString req = QString("select %1 from %2 where %3 between '%4' and '%5'")
                  .arg("RbDate_IDDos","RubriquesHead","RbDate_Date",beginDateStr,endDateStr);
    QSqlQuery qy(m_db);
    if (!qy.exec(req))
    {
        qWarning() << __FILE__ << QString::number(__LINE__) << qy.lastError().text() ;
        }
    while (qy.next())
    {
        QString id = qy.value(0).toString();
        idlist << id;
        }
    idlist.removeDuplicates();
    for (int i = 0; i < listid.count(); ++i )
    {
    	if (idlist.contains(listid[i]))
    	{
    	    listidreturned << listid[i];
    	    }
    	}
    return listidreturned;//ceux de la list listid qui ont consulte entre beginDate et endDate;
}
